import RadarCameraDetction.Radar as Radar
import cv2
import multiprocessing
import flask_video.ObjectDection as od


def OpenCapture(q,mutex,empty,full):
    # 摄像头相关设置
    capture = cv2.VideoCapture(0)
    capture.set(3, 1280)  # width=1280
    capture.set(4, 720)  # height=720
    while True:
        ret, frame = capture.read()
        frame = cv2.flip(frame, 1)  # 镜像操作

        full.acquire()
        mutex.acquire()
        # 消费一个数据
        radarTarget  = q.get()
        mutex.release()
        empty.release()

        frame = od.ObjectDect(frame)
        frame = TagOnPic(radarTarget,frame)

        cv2.imshow("video", frame)

        key = cv2.waitKey(50)
        # print(key)
        if key == ord('q'):  # 判断是哪一个键按下
            break
    cv2.destroyAllWindows()

# 生产者进程
def OpenRadar(q,mutex,empty,full):
    Radar.init()
    ser, error = Radar.Open(9600)
    assert ser != None
    while True:
        empty.acquire()
        # 生产进程
        RadarTarget = Radar.GetData(ser)
        mutex.acquire()
        # 放入缓冲区
        q.put(RadarTarget)
        mutex.release()
        full.release()

def TagOnPic(radarTarget,frame):
    targetnum = radarTarget['RadarTagnum']
    if targetnum == 0:
        return frame
    for item in radarTarget['RadarTaglist']:
        distance = item['distance'] * 1.0 / 100
        posX = int(item['X'])
        posY = int(item['Y'])
        cv2.circle(frame, (posX, posY), 1, (0, 255, 0), 5)
        disstr = "distance = " + str(distance)
        cv2.putText(frame, disstr, (posX - 50, posY - 50), cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 5)
    return frame

def Run():
    # 传递数据的队列 共享单元 默认一次传递一个大小 因此大小位1
    q = multiprocessing.Queue(1)
    # 进程互斥锁 同一时间只能由一个进程访问队列
    mutex = multiprocessing.Semaphore(1)
    # empty表示当前空闲容量 full表示使用容量
    empty = multiprocessing.Semaphore(1)
    full = multiprocessing.Semaphore(0)

    p1 = multiprocessing.Process(target=OpenCapture, args=(q,mutex,empty,full))
    p2 = multiprocessing.Process(target=OpenRadar, args=(q,mutex,empty,full))
    p1.start()
    p2.start()

if __name__ == '__main__':
    Run()






